//
//  ShareManager.m
//  MyShare
//
//  Created by 曹敬贺 on 16/8/15.
//  Copyright © 2016年 北京无限点乐科技有限公司. All rights reserved.
//

#import "ShareManager.h"
#import <UIKit/UIKit.h>



#pragma mark - =====================QQ分享==========================
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/TencentApiInterface.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>

@interface ShareQQManager : NSObject <TencentSessionDelegate,QQApiInterfaceDelegate>

@property (nonatomic, strong) TencentOAuth * tencenOAuth;
@property (nonatomic, strong) NSArray * tencentPermissions;
@property (nonatomic, copy) NSString * appID;
@property (nonatomic, copy)  void(^callBack)(BOOL result);

+ (ShareQQManager *)registerWithAppId:(NSString *)appid;
+ (ShareQQManager *)share;
- (QQApiSendResultCode)sendImage:(UIImage *)image andTitle:(NSString *)title andText:(NSString *)description andDetailURL:(NSString *)url andPlatform:(SharePlatform)platform WithResult:(void (^)(BOOL))block;
- (QQApiSendResultCode)sendWebImage:(NSString *)imageurl WithTitle:(NSString *)title Description:(NSString *)des Platform:(SharePlatform)platform Result:(void(^)(BOOL))block;
+ (BOOL)handleOpenURL:(NSURL *)url;

@end
#pragma mark - ShareQQManager
static  ShareQQManager * qqManager = nil;
static dispatch_once_t ShareQQPredicate;
@implementation ShareQQManager
+ (ShareQQManager *)share
{
    dispatch_once(&ShareQQPredicate, ^{
        if (!qqManager) {
            qqManager = [[super allocWithZone:NULL]init];
        }
    });
    return qqManager;
}
- (id)copy
{
    return [ShareQQManager share];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [ShareQQManager share];
}
+ (ShareQQManager *)registerWithAppId:(NSString *)appid
{
    ShareQQManager * manager = [ShareQQManager share];
    manager.appID = appid;
    [manager.tencenOAuth logout:manager];
    return manager;
}
- (QQApiSendResultCode)sendImage:(UIImage *)image andTitle:(NSString *)title andText:(NSString *)description andDetailURL:(NSString *)url andPlatform:(SharePlatform)platform WithResult:(void (^)(BOOL))block
{
    self.callBack = block;
    QQApiSendResultCode result = -1;
    switch (platform) {
        case SharePlatformQQZone:
        {
            QQApiNewsObject * newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:url] title:title description:description previewImageData:UIImagePNGRepresentation(image) targetContentType:QQApiURLTargetTypeNews];
            SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
            result = [QQApiInterface SendReqToQZone:req];
        }
            break;
        case SharePlatformQQ:
        {
            QQApiNewsObject * newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:url] title:title description:description previewImageData:UIImagePNGRepresentation(image) targetContentType:QQApiURLTargetTypeNews];
            SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
            result = [QQApiInterface sendReq:req];
        }
            break;
        default:
            break;
    }
    [self handleSendResult:result];
    return result;
}
- (QQApiSendResultCode)sendWebImage:(NSString *)imageurl WithTitle:(NSString *)title Description:(NSString *)des Platform:(SharePlatform)platform Result:(void(^)(BOOL))block
{
    self.callBack = block;
    QQApiSendResultCode result = -1;
    
    NSURL * imageUrl = [NSURL URLWithString:imageurl];
    NSData * imageData = [NSData dataWithContentsOfURL:imageUrl];
    if (!imageData) {
        block(NO);
        return result;
    }
    
    switch (platform) {
        case SharePlatformQQZone:
        {
            QQApiImageObject * imageObj = [QQApiImageObject objectWithData:imageData previewImageData:imageData title:title description:des imageDataArray:nil];
            SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:imageObj];
            result = [QQApiInterface SendReqToQZone:req];
        }
            break;
        case SharePlatformQQ:
        {
            QQApiImageObject * imageObj = [QQApiImageObject objectWithData:imageData previewImageData:imageData title:title description:des imageDataArray:nil];
            SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:imageObj];
            result = [QQApiInterface SendReqToQZone:req];
        }
            break;
        default:
            break;
    }
    [self handleSendResult:result];
    return result;
}
- (void)handleSendResult:(QQApiSendResultCode)sendResult
{
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
            NSLog(@"app未注册");
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            NSLog(@"发送参数错误");
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
            NSLog(@"未安装手Q");
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        {
            NSLog(@"API接口不支持");
            break;
        }
        case EQQAPISENDFAILD:
        {
            NSLog(@"发送失败");
            break;
        }
        case EQQAPIQZONENOTSUPPORTTEXT:
        {
            NSLog(@"空间分享不支持QQApiTextObject，请使用QQApiImageArrayForQZoneObject分享");
            break;
        }
        case EQQAPIQZONENOTSUPPORTIMAGE:
        {
            NSLog(@"空间分享不支持QQApiImageObject，请使用QQApiImageArrayForQZoneObject分享");
            break;
        }
        case EQQAPIVERSIONNEEDUPDATE:
        {
            NSLog(@"当前QQ版本太低，需要更新");
            break;
        }
        default:
        {
            break;
        }
    }
}
+ (BOOL)handleOpenURL:(NSURL *)url
{
    ShareQQManager * manager = [ShareQQManager share];
    BOOL result = [QQApiInterface handleOpenURL:url delegate:manager];
    return result;
}
- (void)onReq:(QQBaseReq *)req
{
    
}
- (void)onResp:(QQBaseResp *)resp
{
    ShareQQManager * manager = [ShareQQManager share];
    if (manager.callBack) {
        if ([resp.result isEqualToString:@"0"] && (resp.errorDescription.length == 0)) {
            manager.callBack(YES);
        }else
        {
            manager.callBack(NO);
        }
    }
}
- (void)isOnlineResponse:(NSDictionary *)response
{
    
}
#pragma mark - init
- (TencentOAuth *)tencenOAuth
{
    if (! _tencenOAuth)
    {
        if (self.appID) {
            _tencenOAuth = [[TencentOAuth alloc]initWithAppId:self.appID  andDelegate:self];
        }else
        {
            NSAssert(nil, @"请设置参数appid");
        }
    }
    return _tencenOAuth;
}
- (NSArray *)tencentPermissions
{
    if (! _tencentPermissions)
    {
        _tencentPermissions =  [NSArray arrayWithObjects:@"get_user_info", @"get_simple_userinfo", @"add_t", nil];
    }
    return _tencentPermissions;
}
#pragma mark - TencentLoginDelegate
- (void)tencentDidLogin
{
    
}
- (void)tencentDidNotLogin:(BOOL)cancelled
{
    
}
- (void)tencentDidNotNetWork
{
    
}
- (NSArray *)getAuthorizedPermissions:(NSArray *)permissions withExtraParams:(NSDictionary *)extraParams
{
    return permissions;
}


@end
#pragma mark - ====================WeChat=========================
#import "WXApi.h"
@interface ShareWeChatManager : NSObject<WXApiDelegate>
@property (nonatomic, strong) NSString * appid;
@property (nonatomic, copy)  void(^callBack)(BOOL result);
+ (ShareWeChatManager *)share;
+ (ShareWeChatManager *)registerWithAppId:(NSString *)appid;
- (BOOL)sendMessageWithTitle:(NSString *)title WithDescription:(NSString *)description WithThumbImage:(UIImage *)thumbimage WithDetailURL:(NSString *)url WithPlatform:(SharePlatform)type WithResult:(void(^)(BOOL result))block;
- (BOOL)sendWebImage:(NSString *)imageurl WithTitle:(NSString *)title Description:(NSString *)des Platform:(SharePlatform)platform Result:(void(^)(BOOL))block;
+ (BOOL)handleOpenURL:(NSURL *)url;
@end
static ShareWeChatManager * weChatManager = nil;
static dispatch_once_t ShareWeChatPredicate;
@implementation ShareWeChatManager

+ (ShareWeChatManager *)share
{
    dispatch_once(&ShareWeChatPredicate, ^{
        if (!weChatManager) {
            weChatManager = [[super allocWithZone:NULL]init];
        }
    });
    return weChatManager;
}
- (id)copy
{
    return [ShareWeChatManager share];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [ShareWeChatManager share];
}
+ (ShareWeChatManager *)registerWithAppId:(NSString *)appid
{
    ShareWeChatManager * manager = [ShareWeChatManager share];
    manager.appid = appid;
    [WXApi registerApp:appid];
    return manager;
}
- (BOOL)sendMessageWithTitle:(NSString *)title WithDescription:(NSString *)description WithThumbImage:(UIImage *)thumbimage WithDetailURL:(NSString *)url WithPlatform:(SharePlatform)type WithResult:(void (^)(BOOL))block
{
    self.callBack = block;
    //创建发送对象实例
    SendMessageToWXReq *sendReq = [[SendMessageToWXReq alloc] init];
    sendReq.bText = NO;//不使用文本信息
    switch (type) {
        case SharePlatformWeChatFriend:
            sendReq.scene = 0;
            break;
        case SharePlatformWeChatFriendCircle:
            sendReq.scene = 1;
            break;
        default:
            sendReq.scene = 1;//0 = 好友列表 1 = 朋友圈 2 = 收藏
            break;
    }
    //创建分享内容对象
    WXMediaMessage * mediaMessage = [WXMediaMessage message];
    mediaMessage.title = title;//分享标题
    mediaMessage.description = description;//分享描述
    [mediaMessage setThumbImage:thumbimage];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    
    WXImageObject * imageObj = [WXImageObject object];
    imageObj.imageData = UIImagePNGRepresentation(thumbimage);
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = url;//分享链接
    
    //完成发送对象实例
    mediaMessage.mediaObject = webObj;
    sendReq.message = mediaMessage;
    
    //发送分享信息
    BOOL resultFlag = [WXApi sendReq:sendReq];
    return resultFlag;
}
- (BOOL)sendWebImage:(NSString *)imageurl WithTitle:(NSString *)title Description:(NSString *)des Platform:(SharePlatform)platform Result:(void(^)(BOOL))block
{
    self.callBack = block;
    //创建发送对象实例
    SendMessageToWXReq *sendReq = [[SendMessageToWXReq alloc] init];
    sendReq.bText = NO;//不使用文本信息
    switch (platform) {
        case SharePlatformWeChatFriend:
            sendReq.scene = 0;
            break;
        case SharePlatformWeChatFriendCircle:
            sendReq.scene = 1;
            break;
        default:
            sendReq.scene = 1;//0 = 好友列表 1 = 朋友圈 2 = 收藏
            break;
    }
    //创建分享内容对象
    WXMediaMessage * mediaMessage = [WXMediaMessage message];
    mediaMessage.title = title;//分享标题
    mediaMessage.description = des;//分享描述
    NSURL * imageUrl = [NSURL URLWithString:imageurl];
    NSData * imageData = [NSData dataWithContentsOfURL:imageUrl];
    if (!imageData) {
        block(NO);
        return NO;
    }else
    {
        [mediaMessage setThumbImage:[UIImage imageWithData:imageData]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    }
    WXImageObject * imageObj = [WXImageObject object];
    imageObj.imageData = imageData;
    //完成发送对象实例
    mediaMessage.mediaObject = imageObj;
    sendReq.message = mediaMessage;
    
    //发送分享信息
    return [WXApi sendReq:sendReq];
}
+ (BOOL)handleOpenURL:(NSURL *)url
{
    ShareWeChatManager * manager = [ShareWeChatManager share];
    BOOL result = [WXApi handleOpenURL:url delegate:manager];
    return result;
}
-(void) onReq:(BaseReq*)req
{
}
-(void) onResp:(BaseResp*)resp
{
    ShareWeChatManager * manager = [ShareWeChatManager share];
    if (manager.callBack) {
        if (resp.errCode == 0) {
            manager.callBack(YES);
        }else
        {
            manager.callBack(NO);
        }
    }
}

@end



#pragma mark - ==================SinaWeiboSDK=======================
#import "WeiboSDK.h"
@interface ShareSinaManager : NSObject<WeiboSDKDelegate>
@property (nonatomic, strong) NSString * appid;
@property (nonatomic, strong) NSString * sinaToken;
@property (nonatomic, copy)  void(^callBack)(BOOL result);
+ (ShareSinaManager *)share;
+ (ShareSinaManager *)registerWithAppID:(NSString *)appid;
- (BOOL)sendMessageWithText:(NSString *)text WithImage:(UIImage *)image WithPlatform:(SharePlatform)type WithResult:(void(^)(BOOL result))block;
+ (BOOL)handleOpenURL:(NSURL *)url;
@end
static  ShareSinaManager * sinaManager = nil;
static dispatch_once_t ShareSinaPredicate;
@implementation ShareSinaManager
+ (ShareSinaManager *)share
{
    dispatch_once(&ShareSinaPredicate, ^{
        if (!sinaManager) {
            sinaManager = [[super allocWithZone:NULL]init];
        }
    });
    return sinaManager;
}
- (id)copy
{
    return [ShareSinaManager share];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [ShareSinaManager share];
}

+ (ShareSinaManager *)registerWithAppID:(NSString *)appid
{
    ShareSinaManager * manager = [ShareSinaManager share];
    manager.appid = appid;
    //    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:appid];
    return manager;
}
- (BOOL)sendMessageWithText:(NSString *)text WithImage:(UIImage *)thumbimage WithPlatform:(SharePlatform)type WithResult:(void (^)(BOOL))block
{
    self.callBack = block;
    ShareSinaManager * manager = [ShareSinaManager share];
    
    WBMessageObject *message = [WBMessageObject message];
    message.text = NSLocalizedString(text, nil);
    
    WBImageObject * image = [WBImageObject object];
    if (thumbimage) {
        if (UIImagePNGRepresentation(thumbimage)) {
            image.imageData = UIImagePNGRepresentation(thumbimage);
        }else if (UIImageJPEGRepresentation(thumbimage, 1))
        {
            image.imageData = UIImageJPEGRepresentation(thumbimage, 1);
        }else
        {
            image.imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"default_share" ofType:@"png"]];
        }
    }else
    {
        image.imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"default_share" ofType:@"png"]];
    }
    message.imageObject = image;
    
    //    if ([@"不能同时分享图片和视频" isEqualToString:@"123"])
    //    {
    //        WBWebpageObject * webpage = [WBWebpageObject object];
    //        webpage.objectID = @"identifier1";
    //        webpage.title = NSLocalizedString(@"分享网页标题", nil);
    //        webpage.description = [NSString stringWithFormat:NSLocalizedString(@"分享网页内容简介-%.0f", nil), [[NSDate date] timeIntervalSince1970]];
    //        webpage.thumbnailData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image_2" ofType:@"jpg"]];
    //        webpage.webpageUrl = @"http://sina.cn?a=1";
    //        message.mediaObject = webpage;
    //    }
    
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = @"http://m.hongbaosuoping.com";
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:authRequest access_token:manager.sinaToken];
    //    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
    //                         @"Other_Info_1": [NSNumber numberWithInt:123],
    //                         @"Other_Info_2": @[@"obj1", @"obj2"],
    //                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    request.shouldOpenWeiboAppInstallPageIfNotInstalled = YES;
    return [WeiboSDK sendRequest:request];
}
+ (BOOL)handleOpenURL:(NSURL *)url
{
    ShareSinaManager * manager = [ShareSinaManager share];
    BOOL result = [WeiboSDK handleOpenURL:url delegate:manager];
    return result;
}
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    ShareSinaManager * manager = [ShareSinaManager share];
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        if (manager.callBack) {
            if (sendMessageToWeiboResponse.statusCode == 0) {
                manager.callBack(YES);
            }else
            {
                manager.callBack(NO);
            }
        }
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            manager.sinaToken = accessToken;
        }
        //        NSLog(@"%@",manager.sinaToken);
    }
}

@end

 

 
#pragma mark - ==================Share分享=========================
static  ShareManager * manager = nil;
static dispatch_once_t SharePredicate;
@implementation ShareManager

+ (ShareManager *)share
{
    dispatch_once(&SharePredicate, ^{
        if (!manager) {
            manager = [[super allocWithZone:NULL]init];
        }
    });
    return manager;
}
- (id)copy
{
    return [ShareManager share];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [ShareManager share];
}

+ (void)registerWithAppID:(NSString *)appid andAppKey:(NSString *)key WithPlatform:(SharePlatform)type
{
    switch (type) {
        case SharePlatformQQ:
            [ShareQQManager registerWithAppId:appid];
            break;
        case SharePlatformQQZone:
            [ShareQQManager registerWithAppId:appid];
            break;
        case SharePlatformSina:
            [ShareSinaManager registerWithAppID:appid];
            break;
        case SharePlatformWeChatFriend:
            [ShareWeChatManager registerWithAppId:appid];
            break;
        case SharePlatformWeChatFriendCircle:
            [ShareWeChatManager registerWithAppId:appid];
            break;
        default:
            break;
    }
}
+ (BOOL)shareTopicWithTitle:(NSString *)title WithText:(NSString *)text WithImage:(UIImage *)image WithDetailURL:(NSString *)url WithPlatform:(SharePlatform)type WithResult:(void (^)(BOOL))block
{
    switch (type) {
        case SharePlatformQQ:
        case SharePlatformQQZone:
        {
            QQApiSendResultCode sendResult = [[ShareQQManager share] sendImage:(image ? image : [UIImage imageNamed:@"default_share"]) andTitle:title andText:text andDetailURL:url andPlatform:type WithResult:block];
            if (sendResult == EQQAPISENDSUCESS) {
                return YES;
            }else
            {
                return NO;
            }
        }
            break;
        case SharePlatformSina:
            return [[ShareSinaManager share] sendMessageWithText:title WithImage:image WithPlatform:type WithResult:block];
            break;
        case SharePlatformWeChatFriend:
        case SharePlatformWeChatFriendCircle:
        {
            return [[ShareWeChatManager share]sendMessageWithTitle:title WithDescription:text WithThumbImage:(image ? image : [UIImage imageNamed:@"ShareDefault"]) WithDetailURL:url WithPlatform:type WithResult:block];
        }
            break;
        default:
            return NO;
            break;
    }
}

+ (BOOL)shareTopicWithImageURL:(NSString *)imageurl WithPlatform:(SharePlatform)type WithResult:(void(^)(BOOL result))block
{
    switch (type) {
        case SharePlatformQQ:
        case SharePlatformQQZone:
        {
            QQApiSendResultCode sendResult = [[ShareQQManager share] sendWebImage:imageurl WithTitle:nil Description:nil Platform:type Result:block];
            if (sendResult == EQQAPISENDSUCESS) {
                return YES;
            }else
            {
                return NO;
            }
        }
            break;
        case SharePlatformSina:
            return [[ShareSinaManager share] sendMessageWithText:nil WithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageurl]]] WithPlatform:type WithResult:block];
            break;
        case SharePlatformWeChatFriend:
        case SharePlatformWeChatFriendCircle:
        {
            return [[ShareWeChatManager share]sendWebImage:imageurl WithTitle:nil Description:nil Platform:type Result:block];
        }
            break;
        default:
            return NO;
            break;
    }
}

+ (BOOL)handleOpenURL:(NSURL *)url WithPlatform:(SharePlatform)type
{
    switch (type) {
        case SharePlatformQQ:
        case SharePlatformQQZone:
            return [ShareQQManager handleOpenURL:url];
            break;
        case SharePlatformSina:
            return [ShareSinaManager handleOpenURL:url];
            break;
        case SharePlatformWeChatFriend:
        case SharePlatformWeChatFriendCircle:
            return [ShareWeChatManager handleOpenURL:url];
            break;
        default:
            return NO;
            break;
    }
    return YES;
}

@end


